import { defineStore } from "pinia";
import { ref, computed } from "vue";
import {useRouter} from "vue-router";
import { useUserStore } from "@/stores/userStore";
import { delCartAPI, findCartByIdAPI, insertCartAPI, updateCartItem, delUserCartAPI} from "@/apis/cart.js";
import {ElMessage} from "element-plus";

export const useCartStore = defineStore(
    'cart',
    () => {
        const cartList = ref([]);
        const userStore = useUserStore();
        const isLogin = computed(() => userStore.userInfo.token);
        const router = useRouter();

        // 获取登录后最新购物车列表action
        const updateLoginCartList = async () => {
            const res = await findCartByIdAPI(userStore.userInfo.userId)
            //const res = await findNewCartListAPI()

            // 确保 cartList 总是一个数组
            let updatedCartList = Array.isArray(res.data) ? res.data : [];

            // 更新购物车列表
            cartList.value = updatedCartList;
        }

        const addCart = async (userId,productId,quantity) => {
            if (isLogin.value) {
                //登录之后加入购物车逻辑
                await insertCartAPI(userId,productId,quantity)
                await updateLoginCartList()
            } else {
                ElMessage({type: 'success', message: '请先登录'})
                router.replace({path: '/login'})
            }
        }
        // 删除购物项
        const delCart = async (userId,productId) => {
            if (isLogin.value) {
                //登录之后加入购物车逻辑
                await delCartAPI(userId,productId)
                await updateLoginCartList()
            } else {
                ElMessage({type: 'fail', message: '没有登录，无法删除'})
            }
        }

        const delUserCart = async (userId) => {
            if (isLogin.value) {
                //登录之后加入购物车逻辑
                await delUserCartAPI(userId)
                await updateLoginCartList()
            } else {
                ElMessage({type: 'fail', message: '没有登录，无法删除'})
            }
        }
        // 清除购物车
        const clearCart = () => {
            cartList.value = []
        }
        //修改购物项
        const updateCart = async (userId,productId,quantity) => {
            console.log(userId,productId,quantity)
            if (isLogin.value) {
                await updateCartItem({userId,productId,quantity})
                await updateLoginCartList()
            }
        }
        // const updateCart = async (goods) => {
        //     const { skuId, count, selected } = goods
        //     if (isLogin.value) {
        //         await updateCartItem(skuId, { count, selected })
        //     }
        // }
        
        // 计算属性
        // 1. 总的数量 所有项的count之和
        const allCount = computed(() => cartList.value.reduce((a, c) => a + c.quantity, 0))
        //const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
        // 2. 总价 所有项的count*price之和
        const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.quantity * c.unitPrice, 0))
        //const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
        return {
            cartList,
            addCart,
            delCart,
            allCount,
            allPrice,
            updateLoginCartList,
            clearCart,
            updateCart,
            delUserCart,
        }
    },
    {
        persist: true
    }
)